package com.netflexitysolutions.amazonws.ec2.internal.operations;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.amazonaws.ec2.doc._2009_04_04.DescribeSnapshotsResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeSnapshotsSetItemResponseType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeSnapshotsSetItemType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeSnapshotsSetType;
import com.amazonaws.ec2.doc._2009_04_04.DescribeSnapshotsType;
import com.netflexitysolutions.amazonws.ec2.EC2;
import com.netflexitysolutions.amazonws.ec2.Snapshot;
import com.netflexitysolutions.amazonws.ec2.SnapshotStatus;
import com.netflexitysolutions.amazonws.ec2.internal.ModelUtil;

public class DescribeSnapshotsOperation extends ObjectSetOperationExecutor<DescribeSnapshotsType, List<Snapshot>> {

	public DescribeSnapshotsOperation(EC2 ec2, Set<String> objectIds) {
		super(ec2, objectIds);
	}

	@Override
	protected List<Snapshot> call(DescribeSnapshotsType request) {
		request.setSnapshotSet(createSnapshotsSetElement());
		
		DescribeSnapshotsResponseType response = getEC2().getService().describeSnapshots(request);
		
		List<Snapshot> result =  new ArrayList<Snapshot>();
		if (response.getSnapshotSet() != null) {
			List<DescribeSnapshotsSetItemResponseType> list = response.getSnapshotSet().getItem();
			for (DescribeSnapshotsSetItemResponseType item : list) {
				result.add(toDomainModel(item));
			}
		}
		
		return result;
	}

	private Snapshot toDomainModel(DescribeSnapshotsSetItemResponseType item) {
		Snapshot snapshot = new Snapshot(item.getSnapshotId(), item.getVolumeId(), 
				SnapshotStatus.snapshotStatusForName(item.getStatus()), ModelUtil.toDomainType(item.getStartTime()),
				item.getProgress());	
		return snapshot;
	}

	private DescribeSnapshotsSetType createSnapshotsSetElement() {
		DescribeSnapshotsSetType element = new DescribeSnapshotsSetType();
		List<DescribeSnapshotsSetItemType> list = element.getItem();
		for (String snapshotIds : objectIds) {
			DescribeSnapshotsSetItemType item = new DescribeSnapshotsSetItemType();
			item.setSnapshotId(snapshotIds);
			list.add(item);
		}
		return element;
	}

	
}
